package com.nd.service.wx;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.Utils.CouponUtils;
import com.nd.dao.CartMapper;
import com.nd.dao.CouponMapper;
import com.nd.dao.CouponUserMapper;
import com.nd.pojo.bean.*;
import com.nd.pojo.vo.wx.CouponDataVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CouponWxServiceImpl implements CouponWxService {

    // couponStatus
    private static Short couponStatus0 = 0; //可正常使用
    private static Short couponStatus1 = 1; //已过期
    private static Short couponStatus2 = 2; //已下架

    // CouponUserStatus
    private static Short couponUserStatus0 = 0; //未使用
    private static Short couponUserStatus1 = 1; //已使用
    private static Short couponUserStatus2 = 2; //已过期
    private static Short couponUserStatus3 = 3; //已下架


    private static Short limitValue0 = 0;
    private static Short limitValue1 = 1;



    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    CartMapper cartMapper;


    @Override
    public CouponDataVo query(Short status, Integer page, Integer size) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();

        // 刷新 coupon 和 couponUser 两个表
        CouponUtils.couponRefresh(couponMapper, couponUserMapper, userId);


        PageHelper.startPage(page, size);

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();

        criteria.andUserIdEqualTo(userId).andStatusEqualTo(status);

        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        List<Coupon> coupons = new ArrayList<>();


        if (couponUsers.size() != 0){
            for (CouponUser couponUser : couponUsers) {

                CouponExample couponExample = new CouponExample();
                CouponExample.Criteria criteria1 = couponExample.createCriteria();
                criteria1.andIdEqualTo(couponUser.getCouponId());
                // 查出一个coupon
                List<Coupon> coupons1 = couponMapper.selectByExample((couponExample));
                coupons1.get(0).setStartTime(couponUser.getStartTime());
                coupons1.get(0).setEndTime(couponUser.getEndTime());
                coupons.add(coupons1.get(0));

            }
        }

        PageInfo<Coupon> userPageInfo = new PageInfo<>(coupons);
        long total = userPageInfo.getTotal();

        CouponDataVo couponDataVo = new CouponDataVo();
        couponDataVo.setCount((int)total);
        couponDataVo.setData(coupons);

        return couponDataVo;
    }

    @Override
    public CouponDataVo list(Integer page, Integer size) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();


        if (user != null) {
            Integer userId = user.getId();
            // 刷新 coupon 和 couponUser 两个表
            CouponUtils.couponRefresh(couponMapper, couponUserMapper, userId);

            PageHelper.startPage(page, size);



            // 取优惠券里没到期 且 个数不为-1
            CouponExample couponExample = new CouponExample();
            CouponExample.Criteria criteria = couponExample.createCriteria();

            // 显示不限制领取的优惠券 limit= 0
            // criteria.andStatusEqualTo(couponStatus0).andTotalGreaterThan(-1).andLimitEqualTo(limitValue0);
            criteria.andStatusEqualTo(couponStatus0).andTotalGreaterThan(-1);
            List<Coupon> coupons = couponMapper.selectByExample(couponExample);

            // coupons1 是 limit = 0 的所有
            List<Coupon> coupons1 = new ArrayList<>();
            for (Coupon coupon : coupons) {
                if (coupon.getLimit() == 0){
                    coupons1.add(coupon);
                }
            }


            //List<Coupon> coupons = couponMapper.selectNoLimitCoupon();



            // 用户有限制领取一种购物券的数量， coupon表为limit，如果是0，则是不限制；默认是1，限领一张.
            // 查看用户是否领取该优惠券，如果limit是1，且用户领取了则不显示
            CouponUserExample couponUserExample = new CouponUserExample();
            CouponUserExample.Criteria criteriaUser = couponUserExample.createCriteria();
            criteriaUser.andUserIdEqualTo(userId);

            List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

            // 拿到用户不该领的券
            List<Coupon> couponsUserNoNeed = new ArrayList<>();
            for (CouponUser couponUser : couponUsers) {
                CouponExample couponExamplelimit = new CouponExample();
                CouponExample.Criteria criteriaLimit = couponExamplelimit.createCriteria();
                criteriaLimit.andIdEqualTo(couponUser.getCouponId());
                // 拿到 user的每个优惠券
                List<Coupon> couponsOfUser = couponMapper.selectByExample(couponExamplelimit);
                Short limit = couponsOfUser.get(0).getLimit();
                if (limit == limitValue1){
                    couponsUserNoNeed.add(couponsOfUser.get(0));
                }
            }

            // 取优惠券limit=1
            CouponExample couponExamplelimitAll = new CouponExample();
            CouponExample.Criteria criteriaLimitAll = couponExamplelimitAll.createCriteria();
            //criteriaLimitAll.andLimitEqualTo(limitValue1);

            // 拿到了所有limit=1    coupon2
            List<Coupon> coupons2 = new ArrayList<>();
            List<Coupon> couponsAll = couponMapper.selectByExample(couponExamplelimitAll);
            for (Coupon coupon : couponsAll ){
                if (coupon.getLimit() == 1){

                    coupons2.add(coupon);
                }
            }

            for (Coupon coupon : couponsUserNoNeed) {
                coupons2.remove(coupon);
            }


//        for (Coupon coupon : couponsUserNoNeed) {
//
//            criteriaLimitAll.andIdNotEqualTo(coupon.getId());
//        }
//
//        List<Coupon> couponsLimit = couponMapper.selectByExample(couponExamplelimitAll);


            // 构建结果
            List<Coupon> couponsResult = new ArrayList<>();
            for (Coupon coupon : coupons1) {
                couponsResult.add(coupon);
            }
            for (Coupon coupon : coupons2) {
                couponsResult.add(coupon);
            }



            PageInfo<Coupon> userPageInfo = new PageInfo<>(couponsResult);

            long total = userPageInfo.getTotal();

            CouponDataVo couponDataVo = new CouponDataVo();
            couponDataVo.setCount((int)total);
            couponDataVo.setData(couponsResult);

            return couponDataVo;
        }

        // 刷新 coupon
        //CouponUtils.couponRefresh(couponMapper, couponUserMapper, userId);
        CouponUtils.conponOnlyRefresh(couponMapper);

        PageHelper.startPage(page, size);

        CouponExample couponExample6 = new CouponExample();
        CouponExample.Criteria criteria6 = couponExample6.createCriteria();

        criteria6.andDeletedEqualTo(false).andStatusEqualTo((short)0).andTotalNotEqualTo(-1);

        List<Coupon> coupons = couponMapper.selectByExample(couponExample6);

        PageInfo<Coupon> userPageInfo = new PageInfo<>(coupons);

        long total = userPageInfo.getTotal();

        CouponDataVo couponDataVo2 = new CouponDataVo();
        couponDataVo2.setCount((int)total);
        couponDataVo2.setData(coupons);


        return couponDataVo2;
    }

    @Override
    public Integer receive(Integer couponId) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();

        // 刷新 coupon 和 couponUser 两个表
        CouponUtils.couponRefresh(couponMapper, couponUserMapper, userId);

        // 拿到要领取的conpon
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();

        criteria.andIdEqualTo(couponId);

        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        Date startTime = coupons.get(0).getStartTime();
        Date endTime = coupons.get(0).getEndTime();
        Short days = coupons.get(0).getDays();

        if (coupons.get(0).getTotal() < 0) {
            return -1;
        }

        if (coupons.get(0).getStatus() == 1){
            return 8;
        }

        if (coupons.get(0).getStatus() == 2){
            return 7;
        }



        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteriaUser = couponUserExample.createCriteria();
        criteriaUser.andUserIdEqualTo(userId);

        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        // 拿到用户不该领的券
        List<Coupon> couponsUserNoNeed = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            CouponExample couponExamplelimit = new CouponExample();
            CouponExample.Criteria criteriaLimit = couponExamplelimit.createCriteria();
            criteriaLimit.andIdEqualTo(couponUser.getCouponId());
            // 拿到 user的每个优惠券
            List<Coupon> couponsOfUser = couponMapper.selectByExample(couponExamplelimit);
            Short limit = couponsOfUser.get(0).getLimit();
            if (limit == limitValue1){
                couponsUserNoNeed.add(couponsOfUser.get(0));
            }
        }

        for (Coupon coupon : couponsUserNoNeed) {
            if(coupon.getId() == coupons.get(0).getId()){
                return -2;
            }
        }


        // 构建 userCoupon
        Date endDate = new Date(); //取时间
        Calendar  calendar = new GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE,days); //把日期往后增加一天,整数  往后推,负数往前移动
        endDate=calendar.getTime(); //这个时间就是日期往后推一天的结果


        CouponUser couponUser = new CouponUser();
        couponUser.setUserId(userId);
        couponUser.setCouponId(couponId);
        couponUser.setStatus(couponUserStatus0);
        //couponUser.setUsedTime(null);
        if (endTime != null){
            couponUser.setStartTime(startTime);
            couponUser.setEndTime(endTime);
        }else{
            couponUser.setStartTime(new Date());
            couponUser.setEndTime(endDate);
        }
        //couponUser.setOrderId(null);
        couponUser.setAddTime(coupons.get(0).getAddTime());
        couponUser.setUpdateTime(coupons.get(0).getUpdateTime());
        //couponUser.setDeleted(false);

        int i = couponUserMapper.insertSelective(couponUser);

        if (coupons.get(0).getTotal() == 0){
            // 等于0 为 无限量, 啥都不干
        }else if (coupons.get(0).getTotal() == 1){
            coupons.get(0).setTotal(-1);
        }else {
            coupons.get(0).setTotal(coupons.get(0).getTotal()-1);

        }
        couponMapper.updateByExampleSelective(coupons.get(0), couponExample);


        return i;
    }

    @Override
    public List<Coupon> selectlist(Integer cartId, Integer groupRulesId) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();

        // 刷新 coupon 和 couponUser 两个表
        CouponUtils.couponRefresh(couponMapper, couponUserMapper, userId);

        List<Coupon> couponlist = new ArrayList<>();

        BigDecimal priceSum = new BigDecimal(0);


        if (cartId == 0){
            // cart的价格总和 和 min
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteriaCart = cartExample.createCriteria();
            criteriaCart.andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);

            List<Cart> carts = cartMapper.selectByExample(cartExample);

            for (Cart cart : carts) {
                int num = Integer.parseInt(cart.getNumber() + "");

                priceSum = priceSum.add(cart.getPrice().multiply(new BigDecimal(num)));
            }
            // -------------


        }else {

            Cart cart = cartMapper.selectByPrimaryKey(cartId);

            priceSum = priceSum.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria1 = couponUserExample.createCriteria();
        criteria1.andUserIdEqualTo(userId).andStatusEqualTo(couponStatus0).andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        for (CouponUser couponUser : couponUsers) {
//            CouponExample couponExample = new CouponExample();
//            CouponExample.Criteria criteria = couponExample.createCriteria();

//            criteria.andIdEqualTo(couponUser.getCouponId()).andMinLessThan(priceSum).andDeletedEqualTo(false);
            Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
            if(coupon.getMin().doubleValue()<=priceSum.doubleValue()){
                coupon.setStartTime(couponUser.getStartTime());
                coupon.setEndTime(couponUser.getEndTime());
                couponlist.add(coupon);
            }
        }
        return couponlist;
    }

    @Override
    public Integer exchange(String code) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();

        // 刷新 coupon 和 couponUser 两个表
        CouponUtils.couponRefresh(couponMapper, couponUserMapper, userId);

        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();

        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        Date now = new Date();

        Integer i = 0;

        for (Coupon coupon : coupons) {

            if (code.equals(coupon.getCode())){

                if(coupon.getStatus() != 0){
                    return 9;
                }

                if (coupon.getTotal() < 0) {
                    return -1;
                }

                Date startTime = coupon.getStartTime();
                Date endTime = coupon.getEndTime();
                Short days = coupon.getDays();

                Date endDate = new Date(); //取时间
                Calendar  calendar = new GregorianCalendar();
                calendar.setTime(endDate);
                calendar.add(calendar.DATE,days); //把日期往后增加一天,整数  往后推,负数往前移动
                endDate=calendar.getTime(); //这个时间就是日期往后推一天的结果



                CouponUser couponUser = new CouponUser();

                couponUser.setUserId(userId);

                couponUser.setCouponId(coupon.getId());
                couponUser.setStatus(couponUserStatus0);

                //couponUser.setUsedTime(null);


                if (endTime != null){
                    couponUser.setStartTime(startTime);
                    couponUser.setEndTime(endTime);
                }else{
                    couponUser.setStartTime(now);
                    couponUser.setEndTime(endDate);
                }
                //couponUser.setOrderId(null);
                couponUser.setAddTime(coupon.getAddTime());
                couponUser.setUpdateTime(coupon.getUpdateTime());
                //couponUser.setDeleted(false);

                i = couponUserMapper.insertSelective(couponUser);

                if (i == 1) {
                    if (coupon.getTotal() == 0){
                        // 等于0 为 无限量, 啥都不干
                    }else if (coupon.getTotal() == 1){
                        coupon.setTotal(-1);
                    }else {
                        coupon.setTotal(coupon.getTotal()-1);
                    }

                    CouponExample couponExample1 = new CouponExample();
                    CouponExample.Criteria criteria1 = couponExample1.createCriteria();
                    criteria1.andIdEqualTo(coupon.getId());
                    couponMapper.updateByExampleSelective(coupon, couponExample1);
                }
            }
        }


        return i;
    }



}
